package com.appspot.codelab.docs.client.parts;

import com.appspot.codelab.docs.client.commands.SystemListDirectoryCommand;
import com.appspot.codelab.docs.client.events.CommandEvent;
import com.appspot.codelab.docs.client.repository.RepositoryDirectory;
import com.appspot.codelab.docs.client.widgets.ExplorerTree;
import com.appspot.codelab.docs.client.widgets.ExplorerTree.ExpandHandler;
import com.appspot.codelab.docs.client.widgets.ExplorerTree.SelectionMode;
import com.appspot.codelab.docs.client.widgets.ExplorerTree.SelectionType;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.ScrollPanel;

/**
 * A specialized, non-reusable widget containing the preview panel.
 */
public class ExplorerPart extends Composite {
  
  private ScrollPanel content;
  private ExplorerTree explorer;

  /**
   * Constructs a previewer part.
   */
  public ExplorerPart() {
	content = new ScrollPanel();
    content.setSize("100%", "100%");
	initWidget(content);
  }
  
  public void init(final String project, final String expandTo) {
	explorer = new ExplorerTree(project, expandTo,
		SelectionType.NONE,
		SelectionMode.SINGLE,
	    new ExpandHandler() {
		@Override
		public void getDirectory(final String path,
		    final AsyncCallback<RepositoryDirectory> callback) {
		  CommandEvent.fire(
			  new SystemListDirectoryCommand(path, true,
			      new AsyncCallback<RepositoryDirectory>() {
					@Override
					public void onFailure(Throwable caught) {
					}
					@Override
					public void onSuccess(RepositoryDirectory result) {
					  callback.onSuccess(result);
					}
			  }));
		}
		@Override
		public String getUrl(String itemPath) {
		  if (GWT.isScript()) {
			return "?docpath=" + project + com.google.gwt.http.client.URL.encodeComponent(itemPath);
		  } else {
			return "?gwt.codesvr=3.1.4.20:9997&docpath=" + project + com.google.gwt.http.client.URL.encodeComponent(itemPath);
		  }
		}
	});
	content.setWidget(explorer);
  }
  
  public void refresh(String path) {
	explorer.refresh();
  }

}
